<?php
/**
 *
 *
 */
class Yz_Action_Insert
    extends Yz_Action_Abstract
    implements Yz_Action_Interface
{

    /**
     *  Insert can be performed either w/o fields or values or both
     *  We do not use the case when ones are present in absence of others, so
     *  if values (or fields) had not been set to the action, it will use the no-values clause
     *  @var array
     */
    protected $values = array();


    /************************************
     *          Public methods          *
     ************************************/

    /** @see Yz_Action_Interface::assignFields()
     *  @param hash
     *  @return chainable
     */
    public function assignFields( $fields )
    {
        $fields = new Yz_Hash($fields);
        if (! $fields->isEmpty()) {
            $this->fields = $this->identifyFields($fields);
        }
        return $this;
    }

    /**
     *  @return chainable
     */
    public function assignValues($values)
    {
        $this->values = $this->identifyValues($values);
        return $this;
    }

    /**
     *  @return bool
     */
    public function execute()
    {
        debug();
        $this->statement = $this
            ->buildInsert()
            ->execute();
        return $this;
    }

    /**
     *  @return int
     */
    public function getInsertId()
    {
        return $this->getStatement()->getInsertId();
    }


    /**
     *  Common Insert statement creator
     *  @return Yz_SQL_Statement_Insert
     */
    protected function buildInsert()
    {
        debug();
        $table = $this->tableList->current();
        $sql = \Yz_SQL_Statement_Insert::create()
            ->insert()
            ->into($table)
            ;
        if (0 !== count($this->fields)) {
            // ### ??? if no fields present, what to do with values
            if (0 === count($this->values)) {
                // error
                throw new Yz_Exception("Values are required for Insert with fields");
            }
            $sql
                ->set($this->fields)
                ->bindArray($this->values)
                ;
        }
        return $sql;
    }


}
